package org.yocastlong.mybatisplus.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yocastlong.mybatisplus.common.enums.YesOrNoEnum;
import org.yocastlong.mybatisplus.db.dao.AreaDao;
import org.yocastlong.mybatisplus.db.domain.AreaDO;
import org.yocastlong.mybatisplus.pojo.bo.ThreeLevelAreaBO;
import org.yocastlong.mybatisplus.service.AreaService;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 朱海龙
 * 2025/6/7 13:37
 */
@Service
public class AreaServiceImpl implements AreaService {


    @Autowired
    private AreaDao areaDao;

    @Override
    public List<ThreeLevelAreaBO> threeLevelAreaInfoBOList() {
        List<AreaDO> list = areaDao.lambdaQuery().eq(AreaDO::getStatus, YesOrNoEnum.yes.getStatus()).list();
        if (CollectionUtil.isEmpty(list)) {
            return CollectionUtil.newArrayList();
        }
        Map<String, AreaDO> parentMap = list.stream().filter(it -> it.getLevel() < 5)
                                            .collect(Collectors.toMap(AreaDO::getCode, it -> it));
        List<AreaDO> countyList = list.stream().filter(it -> it.getLevel() >= 5).collect(Collectors.toList());
        List<ThreeLevelAreaBO> boList = CollectionUtil.newArrayList();
        for (AreaDO areaDO : countyList) {
            String parentCode = areaDO.getParentCode();
            String name = areaDO.getName();
            if (StringUtils.isAnyBlank(parentCode, name)) {
                continue;
            }
            AreaDO twoLevelArea = parentMap.get(parentCode);
            if (Objects.isNull(twoLevelArea)) {
                continue;
            }
            String twoLevelAreaCode = twoLevelArea.getCode();
            String twoLevelAreaParentCode = twoLevelArea.getParentCode();
            String twoLevelAreaName = twoLevelArea.getName();
            if (StringUtils.isAnyBlank(twoLevelAreaCode, twoLevelAreaParentCode, twoLevelAreaName)) {
                continue;
            }
            AreaDO oneLeveArea = parentMap.get(twoLevelAreaParentCode);
            if (Objects.isNull(oneLeveArea)) {
                continue;
            }
            String oneLeveAreaCode = oneLeveArea.getCode();
            String oneLevelAreaName = oneLeveArea.getName();

            if (StringUtils.isAnyBlank(oneLeveAreaCode, oneLevelAreaName)) {
                continue;
            }
            ThreeLevelAreaBO threeLevelAreaBO = new ThreeLevelAreaBO();
            threeLevelAreaBO.setThreeLevelAreaCode(oneLeveAreaCode + "," + twoLevelAreaCode + "," + areaDO.getCode());
            threeLevelAreaBO.setThreeLevelAreaName(oneLevelAreaName + "," + twoLevelAreaName + "," + areaDO.getName());
            boList.add(threeLevelAreaBO);
        }

        return boList;
    }
}
